// ignore_for_file: public_member_api_docs, sort_constructors_first
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:photo_manager/photo_manager.dart';

import 'package:pacsun/utils/utils.dart';

class TaskModal {
  final int id;
  final int taskId;
  final int taskconfigid;
  dynamic taskrecordid;
  final String taskName;
  final String resume;
  final Map<String, dynamic> taskReward;
  final double startDate;
  final double endDate;
  final String endDateStr;
  final String description;
  final String bannerUrl;
  final String status;
  // final dynamic createTime;
  final double updateTime;
  final int weight;
  final int isTrial;
  final String playRule;
  final int rewardLimit;
  final int reportDurationMax;
  final String jumpUrl;
  final dynamic platformType;
  final String taskType;
  final int taskPeriod;
  final Map<String, dynamic> contentRewardMap;
  final List<TaskRewardList> taskRewardList;
  final Map<String, dynamic> createUser;
  final Map<String, dynamic> updateUser;
  final String taskCode;
  final String taskInstruction;
  final Map<String, dynamic> taskRecordBo;
  final List<dynamic> productBoList;
  final String taskTypeStr;
  final String platformStr;
  final String platformIconUrl;
  final String subStatus;
  // final String subStatusStr;
  final String subStatusDesc;
  final FrontEndStatus frontEndStatus;
  final List<AuditLog> taskAuditLogList;
  Color? rewardColor;
  final Map<String, dynamic> taskConfig;
  final List<dynamic> taskConfigMediaBoList;
  final TaskConfig? taskConfigModel;

  static const Map<String, String> taskTypeMap = {
    'BEGINNER_TASK': 'Beginner',
    'CONTENT_TASK': 'Content',
    'PRODUCT_TASK': 'Product',
    '': ''
  };
  static const Map<String, String> platformTypeMap = {
    'TIKTOK': 'assets/imgs/tiktok.png',
    'INSTAGRAM': 'assets/imgs/ins.png',
    'YOUTUBE': 'assets/imgs/youtube.png',
    '': ''
  };
  static const Map<String, String> platformStrMap = {
    '1': 'TIKTOK',
    '2': 'INSTAGRAM',
    '3': 'YOUTUBE',
    '': ''
  };

  // My task subStaus to display str
  // static const Map<String, String> subStatusMap = {
  //   'CONTENT_UGC_PENDING_PREVIEW': 'Under Review', // ugc 审核状态
  //   'PRODUCT_UGC_PENDING_PREVIEW': 'Under Review', // ugc 审核状态
  //   'CONTENT_PREVIEW_REJECTED': 'Waiting to Create', // ugc 审核失败
  //   'CONTENT_PREVIEW_APPROVED': 'Waiting to Create&Upload', // ugc 审核通过
  //   'CONTENT_PROOF_PENDING_REVIEW': 'Upload Under Review', // 分享证明审核中
  //   'CONTENT_REVIEW_REJECTED': 'Waiting to Upload ', // 分享证明审核失败
  //   'CONTENT_PROOF_APPROVED': 'Waiting for Settlement ', // 分享证明审核通过
  //   'CONTENT_REWARD_REJECTED': 'Completed ', // 审核发放奖励失败
  //   'BEGINNER_REWARD_COMPLETED': 'Completed ', // 审核发放奖励失败
  //   'CONTENT_COMPLETED': 'Completed', // 种草任务已完成
  //   'BEGINNER_NOT_COMPLETED': 'Not Joined', // 任务未完成
  //   // ''
  // };

  // 奖励文本颜色
  static const Map<String, Color> rewardColorMap = {
    'money': Color(0xFFFFC640),
    'points': Color(0xFF63B9FF)
  };

  TaskModal({
    required this.id,
    required this.taskId,
    required this.taskconfigid,
    required this.taskrecordid,
    required this.taskName,
    required this.resume,
    required this.taskReward,
    required this.startDate,
    required this.endDate,
    required this.endDateStr,
    required this.description,
    required this.bannerUrl,
    required this.status,
    // required this.createTime,
    required this.updateTime,
    required this.weight,
    required this.isTrial,
    required this.playRule,
    required this.rewardLimit,
    required this.reportDurationMax,
    required this.jumpUrl,
    required this.platformType,
    required this.taskType,
    required this.taskPeriod,
    required this.contentRewardMap,
    required this.taskRewardList,
    required this.createUser,
    required this.updateUser,
    required this.taskCode,
    required this.taskInstruction,
    required this.taskRecordBo,
    required this.productBoList,
    required this.taskTypeStr,
    required this.platformStr,
    required this.platformIconUrl,
    required this.subStatus,
    // required this.subStatusStr,
    required this.subStatusDesc,
    required this.frontEndStatus,
    required this.taskAuditLogList,
    this.rewardColor,
    required this.taskConfig,
    required this.taskConfigMediaBoList,
    required this.taskConfigModel,
  });

  factory TaskModal.fromJson(Map<String, dynamic>? json, String? type) {
    // print(json);
    // 优先使用 taskConfig，如果不存在则使用原始 json
    final data = (json == null)
        ? <String, dynamic>{}
        : (type != 'Active' && json['taskConfig'] != null)
            ? json['taskConfig'] as Map<String, dynamic>
            : json;
    String platformTypeValue = '';
    if (data['platformTypeList'] is List) {
      List list = data['platformTypeList'];
      platformTypeValue = list.isNotEmpty ? (list[0]?.toString() ?? '') : '';
    } else {
      platformTypeValue = data['platformType']?.toString() ?? '';
    }

    // contentRewardMap 解析
    Map<String, dynamic> contentRewardMap = {};
    if (data['contentReward'] != null) {
      try {
        (jsonDecode(data['contentReward']) as Map<String, dynamic>)
            .forEach((key, value) {
          if (value is int) {
            contentRewardMap[key] = value;
          } else if (value is String) {
            contentRewardMap[key] = int.tryParse(value) ?? 0;
          }
        });
      } catch (e) {
        contentRewardMap = {};
      }
    }

    dynamic taskrecordid;
    if (json?['taskRecordBo'] != null) {
      taskrecordid = json?['taskRecordBo']?['id'];
    } else {
      if (json?['taskConfig'] != null) {
        taskrecordid = json?['id'];
      } else {
        taskrecordid = null;
      }
    }

    String endDateStr = '';
    if (json?['endDate'] != null) {
      try {
        if (diffDateStartNow(json?['startDate'].toInt() ?? 0)) {
          endDateStr = convertToUSTime(json?['endDate']);
        } else {
          endDateStr = convertToUSTime(json?['startDate']);
        }
      } catch (e) {
        print('e----$e-----${json?['id']}');
      }
    } else {
      endDateStr = '';
    }

    // 列表奖励逻辑 ，优先展示cmp 然后暂时只接发放的奖励
    TaskRewardModel taskReward;
    taskReward = TaskRewardModel.fromJson(data['taskReward'] ?? '');

    Map<String, dynamic> taskRewardMap = {};
    dynamic moneyValue = getRewardValue('money', taskReward, contentRewardMap);
    dynamic pointsValue =
        getRewardValue('points', taskReward, contentRewardMap);
    List<TaskRewardList> taskRewardList = [];
    if (moneyValue != false && int.parse(moneyValue) > 0) {
      taskRewardList
          .add(TaskRewardList.fromJson({'type': 'money', 'value': moneyValue}));
    }
    if (pointsValue != false && int.parse(pointsValue) > 0) {
      taskRewardList.add(
          TaskRewardList.fromJson({'type': 'points', 'value': pointsValue}));
    }
    if (taskRewardList.isNotEmpty) {
      taskRewardMap = {
        'type': taskRewardList[0].type,
        'cmp': taskRewardList[0].value
      };
    }

    // 解析 taskConfig
    TaskConfig? taskConfigModel;
    if (data.isNotEmpty) {
      taskConfigModel = TaskConfig.fromJson(data);
    }

    return TaskModal(
      id: json?['id'] ?? 0,
      taskId: json?['taskId'] ?? 0,
      taskconfigid: data['id'] ?? json?['id'] ?? 0,
      taskrecordid: taskrecordid,
      taskName: data['taskName'] ?? '',
      resume: data['resume'] ?? '',
      taskReward: taskRewardMap,
      startDate: json?['startDate'] ?? 0,
      // endDate: data['endDate'] ?? 0,
      endDate: json?['endDate'] ?? 0,
      endDateStr: endDateStr,
      description: data['description'] ?? '',
      bannerUrl: data['bannerUrl'] ?? '',
      status: json?['status'] ?? data['status'] ?? '',
      // createTime: createTimeStr,
      updateTime: data['updateTime'] ?? 0,
      weight: data['weight'] ?? 0,
      isTrial: data['isTrial'] ?? 0,
      playRule: data['playRule'] ?? '',
      rewardLimit: data['rewardLimit'] ?? 0,
      reportDurationMax: data['reportDurationMax'] ?? 0,
      jumpUrl: data['jumpUrl'] ?? '',
      platformType: data['platformType'] ?? '',
      taskType: data['taskType'] ?? '',
      taskPeriod: data['taskPeriod'] ?? 0,
      contentRewardMap: contentRewardMap,
      taskRewardList: taskRewardList,
      createUser: data['createUser'] ?? {},
      updateUser: data['updateUser'] ?? {},
      taskCode: data['taskCode'] ?? '',
      taskInstruction: data['taskInstruction'] ?? '',
      taskRecordBo: data['taskRecordBo'] ?? {},
      productBoList: data['productBoList'] ?? [],
      subStatus: json?['subStatus'] ?? '',
      // subStatusStr: subStatusMap[json?['subStatus'] ?? ''].toString(),
      subStatusDesc: json?['subStatusDesc'] ?? '',
      // subStatusStr: subStatusMap[json?['subStatus'] ?? ''].toString(),
      frontEndStatus: FrontEndStatus.fromJson(json?['frontEndStatus'] ?? {}),
      taskAuditLogList: (json?['taskAuditLogList'] as List<dynamic>?)
              ?.map((e) => AuditLog.fromJson(e))
              .toList() ??
          [],
      taskTypeStr: TaskModal.taskTypeMap[data['taskType'] ?? ''] ?? '',
      platformStr: platformTypeValue,
      platformIconUrl: TaskModal.platformTypeMap[platformTypeValue] ?? '',
      taskConfig: data,
      taskConfigMediaBoList:
          json?['taskConfigMediaBoList'] ?? data['taskConfigMediaBoList'] ?? [],
      taskConfigModel: taskConfigModel,
    );
  }

  static getRewardValue(String type, TaskRewardModel taskReward,
      Map<String, dynamic> contentReward) {
    if (type == 'money') {
      if (taskReward.cash != null &&
          taskReward.cash?.cpm != null &&
          taskReward.cash!.cpm > 0) {
        return taskReward.cash?.cpm.toString() ?? '';
      } else if (contentReward.isNotEmpty) {
        if (contentReward['cash'] != null && contentReward['cash'] > 0) {
          return contentReward['cash'].toString();
        }
      }
    }
    if (type == 'points') {
      if (taskReward.loyaltyPoints != null &&
          taskReward.loyaltyPoints?.cpm != null &&
          taskReward.loyaltyPoints!.cpm > 0) {
        return taskReward.loyaltyPoints?.cpm.toString() ?? '';
      } else if (taskReward.trackingPoints != null &&
          taskReward.trackingPoints?.cpm != null &&
          taskReward.trackingPoints!.cpm > 0) {
        return taskReward.trackingPoints?.cpm.toString() ?? '';
      } else if (contentReward['loyaltyPoints'] != null &&
          contentReward['loyaltyPoints'] > 0) {
        return contentReward['loyaltyPoints'].toString();
      } else if (contentReward['trackingPoints'] != null &&
          contentReward['trackingPoints'] > 0) {
        return contentReward['trackingPoints'].toString();
      }
    }
    return false;
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'taskId': taskId,
      'taskconfigid': taskconfigid,
      'taskrecordid': taskrecordid,
      'taskName': taskName,
      'resume': resume,
      'taskReward': taskReward,
      'startDate': startDate,
      'endDate': endDate,
      'description': description,
      'bannerUrl': bannerUrl,
      // 'videos': videos,
      'status': status,
      // 'createTime': createTime,
      'updateTime': updateTime,
      'weight': weight,
      'isTrial': isTrial,
      'playRule': playRule,
      'rewardLimit': rewardLimit,
      'reportDurationMax': reportDurationMax,
      'jumpUrl': jumpUrl,
      'platformType': platformType,
      'taskType': taskType,
      'taskPeriod': taskPeriod,
      'contentRewardMap': contentRewardMap,
      'createUser': createUser,
      'updateUser': updateUser,
      'taskCode': taskCode,
      'taskInstruction': taskInstruction,
      'taskRecordBo': taskRecordBo,
      'productBoList': productBoList,
      'taskTypeStr': taskTypeStr,
      'platformStr': platformStr,
      'platformIconUrl': platformIconUrl,
      'taskConfig': taskConfig,
      'frontEndStatus': frontEndStatus.toString(),
      'taskConfigMediaBoList': taskConfigMediaBoList,
    };
  }
}

// 任务相关商品信息
class ProductModel {
  final int id;
  final String name;
  final String description;
  final double price;
  final int stock;
  final int categoryId;
  final String brand;
  final String sku;
  final String status;
  final String? createdAt;
  final String? updatedAt;
  final String imageUrl;

  ProductModel({
    required this.id,
    required this.name,
    required this.description,
    required this.price,
    required this.stock,
    required this.categoryId,
    required this.brand,
    required this.sku,
    required this.status,
    this.createdAt,
    this.updatedAt,
    required this.imageUrl,
  });

  factory ProductModel.fromJson(Map<String, dynamic> json) {
    return ProductModel(
      id: json['id'] ?? 0,
      name: json['name'] ?? '',
      description: json['description'] ?? '',
      price: (json['price'] is int)
          ? (json['price'] as int).toDouble()
          : (json['price'] ?? 0.0).toDouble(),
      stock: json['stock'] ?? 0,
      categoryId: json['categoryId'] ?? 0,
      brand: json['brand'] ?? '',
      sku: json['sku'] ?? '',
      status: json['status'] ?? '',
      createdAt: json['createdAt']?.toString(),
      updatedAt: json['updatedAt']?.toString(),
      imageUrl: json['imageUrl'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'price': price,
      'stock': stock,
      'categoryId': categoryId,
      'brand': brand,
      'sku': sku,
      'status': status,
      'createdAt': createdAt,
      'updatedAt': updatedAt,
      'imageUrl': imageUrl,
    };
  }
}

class FrontEndStatus {
  final List<dynamic> UNDER_REVIEW;
  final List<dynamic> SHARE_CONTENT;
  final List<dynamic> UPLOAD_SCREENSHOT;
  final List<dynamic> SUCCESS;

  FrontEndStatus({
    required this.UNDER_REVIEW,
    required this.SHARE_CONTENT,
    required this.UPLOAD_SCREENSHOT,
    required this.SUCCESS,
  });

  factory FrontEndStatus.fromJson(Map<String, dynamic> json) {
    return FrontEndStatus(
      UNDER_REVIEW: json['UNDER_REVIEW'] ?? [],
      SHARE_CONTENT: json['SHARE_CONTENT'] ?? [],
      UPLOAD_SCREENSHOT: json['UPLOAD_SCREENSHOT'] ?? [],
      SUCCESS: json['SUCCESS'] ?? [],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'UNDER_REVIEW': UNDER_REVIEW,
      'SHARE_CONTENT': SHARE_CONTENT,
      'UPLOAD_SCREENSHOT': UPLOAD_SCREENSHOT,
      'SUCCESS': SUCCESS,
    };
  }

  List<FlowItem> toArray() {
    Map<String, String> iconMap = {
      '1': 'assets/icons/icon_task_flow.svg',
      '2': 'assets/icons/icon_task_flow_success.svg',
      '3': 'assets/icons/icon_task_flow_fail.svg',
    };
    Map<String, String> stepTitle = {
      'UNDER_REVIEW': 'Under Review',
      'SHARE_CONTENT': 'Post to Socials',
      'UPLOAD_SCREENSHOT': 'Provide Link for Claiming Reward',
      'SUCCESS': 'Claim Reward',
    };

    // 上传的icon 单独处理
    String uploadIcon = '';
    if (UPLOAD_SCREENSHOT.isNotEmpty &&
        (UPLOAD_SCREENSHOT[0] == '1' || UPLOAD_SCREENSHOT[0] == '2')) {
      uploadIcon = '1';
    } else {
      if (UPLOAD_SCREENSHOT.isNotEmpty && UPLOAD_SCREENSHOT[0] == '3') {
        uploadIcon = '2';
      } else {
        uploadIcon = '1';
      }
    }

    return [
      FlowItem.fromJson({
        'step': 1,
        'status': UNDER_REVIEW.isNotEmpty ? UNDER_REVIEW[0] : '',
        'icon': UNDER_REVIEW.isNotEmpty ? iconMap[UNDER_REVIEW[0]] : '',
        'title': stepTitle['UNDER_REVIEW'],
        'active': UNDER_REVIEW.isNotEmpty && UNDER_REVIEW[0] != '2',
        'retry': false,
        'statusStr': UNDER_REVIEW.isNotEmpty ? UNDER_REVIEW[1] : '',
      }),
      FlowItem.fromJson({
        'step': 2,
        'status': SHARE_CONTENT.isNotEmpty ? SHARE_CONTENT[0] : '',
        'icon': SHARE_CONTENT.isNotEmpty ? iconMap[SHARE_CONTENT[0]] : '',
        'title': stepTitle['SHARE_CONTENT'],
        'active': SHARE_CONTENT.isNotEmpty && SHARE_CONTENT[0] != '2',
        'retry': false,
        'statusStr': SHARE_CONTENT.isNotEmpty ? SHARE_CONTENT[1] : '',
      }),
      FlowItem.fromJson({
        'step': 3,
        'status': UPLOAD_SCREENSHOT.isNotEmpty ? UPLOAD_SCREENSHOT[0] : '',
        'icon': UPLOAD_SCREENSHOT.isNotEmpty ? iconMap[uploadIcon] : '',
        'title': stepTitle['UPLOAD_SCREENSHOT'],
        'active': UPLOAD_SCREENSHOT.isNotEmpty &&
            (UPLOAD_SCREENSHOT[0] == '2' ||
                UPLOAD_SCREENSHOT[0] == '4' ||
                UPLOAD_SCREENSHOT[0] == '1'),
        'retry': SHARE_CONTENT.isNotEmpty && UPLOAD_SCREENSHOT[0] == '4',
        'statusStr': UPLOAD_SCREENSHOT.isNotEmpty ? UPLOAD_SCREENSHOT[1] : '',
      }),
      FlowItem.fromJson({
        'step': 4,
        'status': SUCCESS.isNotEmpty ? SUCCESS[0] : '',
        'icon': SUCCESS.isNotEmpty ? iconMap[SUCCESS[0]] : '',
        'title': stepTitle['SUCCESS'],
        'active': SUCCESS.isNotEmpty,
        'retry': false,
        'statusStr': SUCCESS.isNotEmpty ? SUCCESS[1] : '',
      })
    ];
  }
}

class FlowItem {
  final int step;
  final String status;
  final String icon;
  final String title;
  final String statusStr;
  final bool active;
  final bool retry;
  FlowItem({
    required this.step,
    required this.status,
    required this.icon,
    required this.title,
    required this.statusStr,
    required this.active,
    required this.retry,
  });
  factory FlowItem.fromJson(Map<String, dynamic> json) {
    return FlowItem(
      step: json['step'] ?? '',
      status: json['status'] ?? '',
      statusStr: json['statusStr'] ?? '',
      icon: json['icon'] ?? '',
      title: json['title'] ?? '',
      active: json['active'] ?? false,
      retry: json['retry'] ?? false,
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'step': step,
      'status': status,
      'icon': icon,
      'title': title,
      'active': active,
    };
  }
}

// 审核记录
class AuditLog {
  final int id;
  final int taskRecordId;
  final String auditStatus;
  final String contentTitle;
  final String contentThumbnail;
  final String auditRemark;
  final double createTime;
  final double updateTime;
  final dynamic taskRecord;
  final dynamic bgcContent;
  final int contentId;

  AuditLog({
    required this.id,
    required this.taskRecordId,
    required this.auditStatus,
    required this.contentTitle,
    required this.contentThumbnail,
    required this.auditRemark,
    required this.createTime,
    required this.updateTime,
    this.taskRecord,
    required this.bgcContent,
    required this.contentId,
  });

  factory AuditLog.fromJson(Map<String, dynamic> json) {
    return AuditLog(
      id: json['id'] ?? 0,
      taskRecordId: json['taskRecordId'] ?? 0,
      auditStatus: json['auditStatus'] ?? '',
      contentTitle: json['contentTitle'] ?? '',
      contentThumbnail: json['contentThumbnail'] ?? '',
      auditRemark: json['auditRemark'] ?? '',
      createTime: json['createTime'] ?? 0,
      updateTime: json['updateTime'] ?? 0,
      taskRecord: json['taskRecord'] ?? '',
      bgcContent: json['bgcContent'] ?? '',
      contentId: json['contentId'] ?? 0,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'taskRecordId': taskRecordId,
      'auditStatus': auditStatus,
      'contentTitle': contentTitle,
      'contentThumbnail': contentThumbnail,
      'auditRemark': auditRemark,
      'createTime': createTime,
      'updateTime': updateTime,
      'taskRecord': taskRecord,
      'bgcContent': bgcContent,
      'contentId': contentId,
    };
  }
}

class UploadModel {
  bool startUpload;
  bool endUpload;
  bool errorUpload;
  bool successUpload;
  int progress;
  AssetEntity assetEntity;
  UploadModel({
    required this.startUpload,
    required this.endUpload,
    required this.errorUpload,
    required this.successUpload,
    required this.progress,
    required this.assetEntity,
  });

  factory UploadModel.fromJson(Map<String, dynamic> json) {
    return UploadModel(
      startUpload: json['startUpload'] ?? false,
      endUpload: json['endUpload'] ?? false,
      errorUpload: json['errorUpload'] ?? false,
      successUpload: json['successUpload'] ?? false,
      assetEntity: json['assetEntity'] ?? false,
      progress: json['progress'] ?? 0.0,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'startUpload': startUpload,
      'endUpload': endUpload,
      'errorUpload': errorUpload,
      'successUpload': successUpload,
      'progress': progress,
    };
  }

  String toJson() => json.encode(toMap());
}

class RewardDetail {
  final int cpm;
  final int total;
  final String type;

  RewardDetail({required this.cpm, required this.total, required this.type});

  factory RewardDetail.fromJson(Map<String, dynamic> json) {
    return RewardDetail(
      cpm: json['cpm'],
      total: json['total'],
      type: json['type'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'cpm': cpm,
      'total': total,
      'type': type,
    };
  }
}

class TaskRewardModel {
  final RewardDetail? loyaltyPoints;
  final RewardDetail? cash;
  final RewardDetail? trackingPoints;

  TaskRewardModel({
    this.loyaltyPoints,
    this.cash,
    this.trackingPoints,
  });

  factory TaskRewardModel.fromJson(dynamic json) {
    if (json == null || (json is String && json.isEmpty)) {
      return TaskRewardModel();
    }
    if (json is String) {
      json = jsonDecode(json);
    }
    return TaskRewardModel(
      loyaltyPoints: json['loyaltyPoints'] != null
          ? RewardDetail.fromJson(json['loyaltyPoints'])
          : null,
      cash: json['cash'] != null ? RewardDetail.fromJson(json['cash']) : null,
      trackingPoints: json['trackingPoints'] != null
          ? RewardDetail.fromJson(json['trackingPoints'])
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'loyaltyPoints': loyaltyPoints?.toJson(),
      'cash': cash?.toJson(),
      'trackingPoints': trackingPoints?.toJson(),
    };
  }
}

class TaskRewardList {
  final String type;
  final String value;

  TaskRewardList({required this.type, required this.value});

  factory TaskRewardList.fromJson(Map<String, String> json) {
    return TaskRewardList(
      type: json['type'] ?? '',
      value: json['value'] ?? '',
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'type': type,
      'value': value,
    };
  }

  factory TaskRewardList.fromMap(Map<String, dynamic> map) {
    return TaskRewardList(
      type: map['type'] as String,
      value: map['value'] as String,
    );
  }

  String toJson() => json.encode(toMap());
}

// contentBo
class ContentBo {
  final int id;
  final String title;
  final String richContent;
  final String thumbnail;
  // final List<String> images;
  final int taskRecordId;
  final String status;

  ContentBo({
    required this.id,
    required this.title,
    required this.richContent,
    required this.thumbnail,
    // required this.images,
    required this.taskRecordId,
    required this.status,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'id': id,
      'title': title,
      'richContent': richContent,
      // 'images': images,
      'taskRecordId': taskRecordId,
      'status': status,
    };
  }

  factory ContentBo.fromMap(Map<String, dynamic> map) {
    return ContentBo(
      id: map['id'] as int,
      title: map['title'] as String,
      richContent: map['richContent'] as String,
      thumbnail: map['thumbnail'] ?? '',
      taskRecordId: map['taskRecordId'] as int,
      // images: List<String>.from(map['images'] as List<dynamic>),
      status: map['status'],
    );
  }

  String toJson() => json.encode(toMap());

  factory ContentBo.fromJson(Map<String, dynamic> source) =>
      ContentBo.fromMap(source);
  @override
  String toString() {
    return 'ContentBo(id: $id, title: $title, richContent: $richContent,  taskRecordId: $taskRecordId)';
  }

  @override
  bool operator ==(covariant ContentBo other) {
    if (identical(this, other)) return true;

    return other.id == id &&
        other.title == title &&
        other.richContent == richContent &&
        // listEquals(other.images, images) &&
        other.taskRecordId == taskRecordId;
  }

  @override
  int get hashCode {
    return id.hashCode ^
        title.hashCode ^
        richContent.hashCode ^
        // images.hashCode ^
        taskRecordId.hashCode;
  }
}

// 分享反馈Model
class ReportData {
  final String contentUrl;
  final List<String> content;

  ReportData({required this.contentUrl, required this.content});

  ReportData copyWith({
    String? contentUrl,
    List<String>? content,
  }) {
    return ReportData(
      contentUrl: contentUrl ?? this.contentUrl,
      content: content ?? this.content,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'contentUrl': contentUrl,
      'content': content,
    };
  }

  factory ReportData.fromMap(Map<String, dynamic> map) {
    return ReportData(
      contentUrl: map['contentUrl'],
      content: (map['content'] as List)
          .whereType<String>() // 只保留字符串
          .toList(),
    );
  }

  String toJson() => json.encode(toMap());
}

// 任务示例视频/图片
class MediaBoList {
  final int id;
  final int taskConfigId;
  final int mediaType; // 1图片 2 视频
  final String url; // 资源路径
  final String thumbnall; // 资源路径
  MediaBoList({
    required this.id,
    required this.taskConfigId,
    required this.mediaType,
    required this.url,
    required this.thumbnall,
  });

  MediaBoList copyWith({
    int? id,
    int? taskConfigId,
    int? mediaType,
    String? url,
    String? thumbnall,
  }) {
    return MediaBoList(
      id: id ?? this.id,
      taskConfigId: taskConfigId ?? this.taskConfigId,
      mediaType: mediaType ?? this.mediaType,
      url: url ?? this.url,
      thumbnall: thumbnall ?? this.thumbnall,
    );
  }

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'id': id,
      'taskConfigId': taskConfigId,
      'mediaType': mediaType,
      'url': url,
    };
  }

  factory MediaBoList.fromMap(Map<String, dynamic> map) {
    return MediaBoList(
      id: map['id'] as int,
      taskConfigId: map['taskConfigId'] as int,
      mediaType: map['mediaType'] as int,
      url: map['url'] as String,
      thumbnall: map['thumbnail'] ?? '',
    );
  }

  String toJson() => json.encode(toMap());

  @override
  String toString() {
    return 'MediaBoList(id: $id, taskConfigId: $taskConfigId, mediaType: $mediaType, url: $url)';
  }

  @override
  bool operator ==(covariant MediaBoList other) {
    if (identical(this, other)) return true;

    return other.id == id &&
        other.taskConfigId == taskConfigId &&
        other.mediaType == mediaType &&
        other.url == url;
  }

  @override
  int get hashCode {
    return id.hashCode ^
        taskConfigId.hashCode ^
        mediaType.hashCode ^
        url.hashCode;
  }
}

// 添加 TaskConfig 模型类
class TaskConfig {
  final int? id;
  final String? taskName;
  final String? description;
  final List<ProductModel>? productBoList;
  final List<dynamic>? taskTagBoList; // 使用 dynamic，避免循环引用

  TaskConfig({
    this.id,
    this.taskName,
    this.description,
    this.productBoList,
    this.taskTagBoList,
  });

  factory TaskConfig.fromJson(Map<String, dynamic> json) {
    return TaskConfig(
      id: json['id'],
      taskName: json['taskName'],
      description: json['description'],
      productBoList: json['productBoList'] != null
          ? (json['productBoList'] as List)
              .map((e) => ProductModel.fromJson(e))
              .toList()
          : null,
      taskTagBoList: json['taskTagBoList'], // 直接存储原始数据
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'taskName': taskName,
      'description': description,
      'productBoList': productBoList?.map((e) => e.toJson()).toList(),
      'taskTagBoList': taskTagBoList,
    };
  }
}
